package b1.controls.basic
{
	import flash.display.*;
	import flash.events.*;
	import flash.utils.*;

	public class BasicMc extends Sprite
	{
		public var fps:Number;
		public var mc:MovieClip;
		private var lastUpdateTime:Number;
		private var loopFlag:Boolean;
		public static const ON_MOVIE_FINISH:String = "OnMovieFinish";
		public var eventDispatcher:EventDispatcher;
		
		public function BasicMc(McClass:Class, fps:Number = 10, loopFlag:Boolean = true)
		{
			super();
			lastUpdateTime = 0;
			this.fps = fps;
			mc = new McClass();
			mc.stop();
			if (fps != 0)
				mc.addEventListener(Event.ENTER_FRAME, onEnterFrame);
			if (fps < 0)
				mc.gotoAndStop(mc.totalFrames);
			eventDispatcher = new EventDispatcher();
			this.loopFlag = loopFlag;
			addChild(mc);
		}
		
		private function onEnterFrame(event:Event):void
		{
			var currentTime:Number = getTimer();
			var interval:Number = currentTime - lastUpdateTime;
			if (fps > 0)
			{
				if ((loopFlag || !loopFlag && mc.currentFrame < mc.totalFrames) && interval > 1000 / fps)
				{
					mc.gotoAndStop(mc.currentFrame % mc.totalFrames + 1);
					lastUpdateTime = currentTime;
				}
				else if (!loopFlag && mc.currentFrame >= mc.totalFrames)
				{
					eventDispatcher.dispatchEvent(new Event(ON_MOVIE_FINISH));
					mc.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
				}
			}
			else
			{
				if ((loopFlag || !loopFlag && mc.currentFrame > 1) && interval > -1000 / fps)
				{
					if (mc.currentFrame > 1)
						mc.gotoAndStop(mc.currentFrame - 1);
					else
						mc.gotoAndStop(mc.totalFrames);
					lastUpdateTime = currentTime;
				}
				else if (!loopFlag && mc.currentFrame <= 1)
				{
					eventDispatcher.dispatchEvent(new Event(ON_MOVIE_FINISH));
					mc.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
				}
			}
		}
		
	}
}